import socket
from threading import Thread

IP = '127.0.0.1'
PORT = 5000

ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss.bind((IP, PORT))
ss.listen()
print(f"Chat Server Run on {IP}:{PORT} ...")

client_sockets = []


def on_client_connect(client_socket, addr):
    print(f"Begin to listen a client {addr}")
    
    while True:
        try:
            msg = client_socket.recv(100)

            if len(msg) <= 0:
                break

            broadcast(msg)
        except:
            break


    # 结束后，从客户列表中删除自己
    print(f"Connection {addr} closed.")
    if client_socket in client_sockets:
        client_sockets.remove(client_socket)


def broadcast(msg):
    print(f"Begin to broadcast msg: {msg.decode('utf-8')}")
    for cs in client_sockets:
        cs.send(msg)


while True:
    cs, ca = ss.accept()
    print(f'Connection established: {ca}')
    cs.send(bytes("Welcome to my chat server.", "utf-8"))
    client_sockets.append(cs)
    t = Thread(target=on_client_connect, args=(cs, ca))
    t.start()
